<template>
  <div class="security-settings">
    <h2>安全设置</h2>
    <el-divider />
    
    <!-- 修改密码 -->
    <div class="security-item">
      <div class="item-header">
        <span class="title">账户密码</span>
        <el-button type="text" @click="showPasswordDialog = true">修改</el-button>
      </div>
      <div class="item-desc">当前密码强度：{{ passwordStrength }}</div>
    </div>
    
    <!-- 绑定手机 -->
     <div class="security-item">
      <div class="item-header">
        <span class="title">绑定手机</span>
        <el-button 
          type="text" 
          @click="showPhoneDialog = true"
        >
          {{ currentPhone ? '更换' : '绑定' }}
        </el-button>
      </div>
      <div class="item-desc">
        {{ currentPhone ? `已绑定手机：${formatPhone(currentPhone)}` : '未绑定手机' }}
      </div>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog 
      v-model="showPasswordDialog" 
      title="修改密码" 
      width="30%"
      @closed="resetPasswordForm"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            show-password
            placeholder="请输入当前密码"
            @blur="validateOldPassword"
          />
          <div v-if="passwordForm.oldPasswordError" class="error-message">
            {{ passwordForm.oldPasswordError }}
          </div>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            show-password
            placeholder="6-20位字母、数字或符号"
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleChangePassword"
          :loading="passwordLoading"
          :disabled="!isPasswordFormValid"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 绑定手机对话框 -->
    <el-dialog 
      v-model="showPhoneDialog" 
      :title="currentPhone ? '更换手机号' : '绑定手机号'" 
      width="30%"
      @closed="resetPhoneForm"
    >
      <el-form 
        :model="phoneForm" 
        :rules="phoneRules" 
        ref="phoneFormRef"
        label-width="100px"
      >
        <template v-if="currentPhone">
          <el-form-item label="原手机号" prop="oldPhone">
            <el-input 
              v-model="phoneForm.oldPhone" 
              placeholder="请输入原手机号"
              @blur="validateOldPhone"
            />
            <div v-if="phoneForm.oldPhoneError" class="error-message">
              {{ phoneForm.oldPhoneError }}
            </div>
          </el-form-item>
        </template>
        
        <el-form-item label="新手机号" prop="newPhone">
          <el-input 
            v-model="phoneForm.newPhone" 
            placeholder="请输入新手机号"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showPhoneDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleBindPhone"
          :loading="phoneLoading"
          :disabled="!isPhoneFormValid"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  phone: String,
  password: String // 从父组件接收当前密码
})

const emit = defineEmits(['update:phone', 'password-change'])

// 当前手机号
const currentPhone = ref(props.phone)

// 密码相关
const showPasswordDialog = ref(false)
const passwordFormRef = ref(null)
const passwordLoading = ref(false)
const passwordStrength = ref('强')

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  oldPasswordError: ''
})

// 手机绑定相关
const showPhoneDialog = ref(false)
const phoneFormRef = ref(null)
const phoneLoading = ref(false)

const phoneForm = ref({
  oldPhone: '',
  newPhone: '',
  oldPhoneError: ''
})

// 计算属性：密码表单是否有效
const isPasswordFormValid = computed(() => {
  return passwordForm.value.oldPassword && 
         passwordForm.value.newPassword && 
         passwordForm.value.confirmPassword &&
         !passwordForm.value.oldPasswordError
})

// 计算属性：手机表单是否有效
const isPhoneFormValid = computed(() => {
  if (currentPhone.value) {
    return phoneForm.value.oldPhone && 
           phoneForm.value.newPhone &&
           !phoneForm.value.oldPhoneError
  }
  return phoneForm.value.newPhone
})

// 验证旧密码
const validateOldPassword = () => {
  console.log(props.password);
  
  if (passwordForm.value.oldPassword !== props.password) {
    passwordForm.value.oldPasswordError = '旧密码不正确'
  } else {
    passwordForm.value.oldPasswordError = ''
  }
}

// 验证旧手机号
const validateOldPhone = () => {
  if (phoneForm.value.oldPhone !== currentPhone.value) {
    phoneForm.value.oldPhoneError = '原手机号不正确'
  } else {
    phoneForm.value.oldPhoneError = ''
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    // 再次验证旧密码
    if (passwordForm.value.oldPassword !== props.password) {
      passwordForm.value.oldPasswordError = '旧密码不正确'
      return
    }
    
    passwordLoading.value = true
    
    await axios.post('/api/auth/updatePassword', {
      password: passwordForm.value.newPassword,
      id: localStorage.getItem('id')
    })
    
    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false
    emit('password-change')
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'validate') {
      ElMessage.error('密码修改失败')
    }
  } finally {
    passwordLoading.value = false
  }
}

// 绑定/更换手机号
const handleBindPhone = async () => {
  try {
    await phoneFormRef.value.validate()
    
    // 如果是更换手机号，验证旧手机号
    if (currentPhone.value && phoneForm.value.oldPhone !== currentPhone.value) {
      phoneForm.value.oldPhoneError = '原手机号不正确'
      return
    }
    
    phoneLoading.value = true
    
    await axios.post('/api/auth/udatePhone', {
      phone: phoneForm.value.newPhone,
      id: localStorage.getItem('id')
    })
    
    ElMessage.success(currentPhone.value ? '手机号更换成功' : '手机号绑定成功')
    currentPhone.value = phoneForm.value.newPhone
    emit('update:phone', phoneForm.value.newPhone)
    showPhoneDialog.value = false
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'validate') {
      ElMessage.error(currentPhone.value ? '手机号更换失败' : '手机号绑定失败')
    }
  } finally {
    phoneLoading.value = false
  }
}

// 新增手机号格式化函数
const formatPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{3})/, '$1****$2')
}

// 重置表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    oldPasswordError: ''
  }
}

const resetPhoneForm = () => {
  phoneFormRef.value?.resetFields()
  phoneForm.value = {
    oldPhone: '',
    newPhone: '',
    oldPhoneError: ''
  }
}

// 监听父组件传入的手机号变化
watch(() => props.phone, (newVal) => {
  currentPhone.value = newVal
})
</script>

<style scoped>
.security-settings {
  padding: 10px;
}

.security-item {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.security-item:last-child {
  border-bottom: none;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.title {
  font-size: 16px;
  font-weight: 500;
}

.item-desc {
  color: #909399;
  font-size: 14px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}
</style>